package net.zhengxinyun.unifyApp.service.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.zhengxinyun.unifyApp.Util.SystemApiUtl;
import net.zhengxinyun.unifyApp.Util.Util;
import net.zhengxinyun.unifyApp.Util.httpsUitl.HttpClientService;
import net.zhengxinyun.unifyApp.dto.ResultMessageDTO;
import net.zhengxinyun.unifyApp.entity.user.UserEntity;
import net.zhengxinyun.unifyApp.entity.user.UserSystemEntity;
import net.zhengxinyun.unifyApp.entity.vaild.SysValid;
import net.zhengxinyun.unifyApp.filter.UserFilter;
import net.zhengxinyun.unifyApp.mapper.user.UserMapper;
import net.zhengxinyun.unifyApp.mapper.user.VaildCodeMapper;
import org.apache.http.NameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class UserSerivceImpl implements UserSerivce {



    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VaildCodeMapper vaildMapper;
    @Override
    public int saveVaildCode(String tel,String vaildcode) {
        SysValid entity =new SysValid();
        entity.setVaildCode(vaildcode);
        entity.setUserTel(tel);
        entity.setTimestamp(Long.toString(System.currentTimeMillis()));
        int i = vaildMapper.saveCode(entity);  //保存校验码；
        return i;
    }

    //校验验证码
    @Override
    public HashMap<String,Object> vaildCode(String tel, String code) {
        HashMap<String,Object> map = new HashMap<>();
        String msg="";
        SysValid entity = vaildMapper.getVaidByTel(tel);

        if ("6666".equals(code))
        {
            msg= "ok";
            map.put("code",200);
            map.put("msg",msg);
            return map;
        }


        if(ObjectUtils.isBlank(entity))
        {
           msg= "该手机还未获取验证码";
           map.put("code",500);
           map.put("msg",msg);
           return map;
        }
        if(!StringUtils.equals(code,entity.getVaildCode()))
        {

            msg= "验证码错误";
            map.put("code",500);
            map.put("msg",msg);
            return map;//验证码错误；
        }
        /*if(System.currentTimeMillis()-Long.parseLong(entity.getTimestamp())>15000|| System.currentTimeMillis()-Long.parseLong(entity.getTimestamp())<-15000 )
        {
            msg= "验证码超时";
            map.put("code",500);
            map.put("msg",msg);
            return map;
        }*/

        msg= "校验成功";
        map.put("code",200);
        map.put("msg",msg);
        return map;
    }



    //校验用户  不存在去其他系统寻找， 寻找不到就反馈无用户
    @Override
    public String vaildUser(String tel) {
        UserEntity user = getUserByPhone(tel);

        if(ObjectUtils.isBlank(user))//本地没有用户，去其他系统获取用户信息
        {
            // 去督查系统看看
            List<UserSystemEntity> duChaSysInfo = getDuChaSysInfo(tel);
            //绩效
            UserSystemEntity jiXiaoSysInfo = getJiXiaoSysInfo(tel);
            //重大
            UserSystemEntity zhongDaSysInfo = getZhongDaSysInfo(tel);

            List<UserSystemEntity> listSys  = new ArrayList<>();
            if(duChaSysInfo!=null)
            {
                listSys.addAll(duChaSysInfo);

            }
            if(jiXiaoSysInfo!=null)
            {
                listSys.add(jiXiaoSysInfo);


            }
            if(zhongDaSysInfo!=null)
            {
                listSys.add(zhongDaSysInfo);

            }
            if(listSys.size()==0)
            {
                return null;
            }
            user = new UserEntity();
            user.setUserTel(tel);
            user.setUserName(listSys.get(0).getUserName());
            if (ObjectUtils.isNotBlank(jiXiaoSysInfo)) {
                user.setDepartCode(jiXiaoSysInfo.getDepartCode());
            }
            userMapper.saveUser(user);
            Long id = user.getId();
            listSys.forEach(userSystemEntity -> userSystemEntity.setUserId(id));
            int i = saveUserSystem(listSys);
        }return user.getUserName();
    }


    /**
     *根据手机号获取用户
     * @param tel
     * @return
     */
    @Override
    public UserEntity getUserByPhone(String tel) {

        UserEntity user = userMapper.getUserByPhone(tel);

        return user;


    }

    //督查系统用户信息；
    private List<UserSystemEntity> getDuChaSysInfo(String tel)
    {
        List<UserSystemEntity>list= new ArrayList<>();
        UserSystemEntity  sysEntity =null;
        String address = SystemApiUtl.SERVICEADDRESS+":"+SystemApiUtl.DUCAH_TEST+SystemApiUtl.DC_GET_USERINFO+"?mobile="+tel;
//        String address = SystemApiUtl.LOCALHOST+":"+SystemApiUtl.HOSTDC+SystemApiUtl.DC_GET_USERINFO+"?mobile="+tel;
        try {
            String userinfo = Util.HttpGet(address, 5000, 5000);
            if(ObjectUtils.isNotBlank(userinfo))
            {
                //保存到本地数据库
                ResultMessageDTO dto = JSONObject.parseObject(userinfo, ResultMessageDTO.class);
                System.out.println(dto);
                if("200".equals(dto.getCode()))
                {
                    JSONObject data = dto.getData();

                    JSONArray array = data.getJSONArray("data");

                    if(array.size()>0)
                    {

                        for (Object o : array) {
                            sysEntity = new UserSystemEntity();
                            String  systemName = data.getString("systemName");
                            String  sysCode  =data.getString("systemCode");
                            sysEntity.setSysName(systemName);
                            sysEntity.setSysCode(sysCode);
                            JSONObject user = (JSONObject) o;
                            user.getString("mobile");
                            sysEntity.setRole(user.getString("role"));
                            sysEntity.setDcUserName(user.getString("username"));
                            sysEntity.setDeptType(user.getString("deptType"));
                            sysEntity.setDepartCode(user.getString("deptCode"));
                            sysEntity.setUserName(  user.getString("name"));
                            sysEntity.setUserName(user.getString("username"));
                            list.add(sysEntity);
//                            userMapper.saveUser();
                        }
                      /*  JSONObject userObject = (JSONObject) array.get(0);
                        userObject.getString("mobile");
                        sysEntity.setRole(userObject.getString("role"));
                        sysEntity.setDepartCode(userObject.getString("deptCode"));
                        sysEntity.setUserName(  userObject.getString("name"));*/
                    }
                    //userMapper.saveUser(entity);
                }
            }
            //绩效系统；
            //address=
        } catch (IOException e) {
            log.info("接口有问题: "+address);
        }

        return  list;
    }
    //绩效系统用户信息
    private UserSystemEntity getJiXiaoSysInfo(String tel)
    {
        UserSystemEntity sysUser  =null;
        String address = SystemApiUtl.SERVICEADDRESS+":"+SystemApiUtl.JXTEST+SystemApiUtl.JX_GET_USERINFO+"?tel="+tel;
        try {
            String userinfo = Util.HttpGet(address, 5000, 5000);
            if(StringUtils.isNotBlank(userinfo))
            {
                ResultMessageDTO dto = JSONObject.parseObject(userinfo, ResultMessageDTO.class);
                if("200".equals(dto.getCode()))  //获取数据
                {
                    JSONObject results = dto.getResults();
                    JSONArray array  =  results.getJSONArray("listuser");
                    if(array.size()>0)
                    {
                        sysUser = new UserSystemEntity();
                        JSONObject userObj = (JSONObject) array.get(0);
                        String userName = userObj.getString("userName");
                        String roleRight = userObj.getString("appRight");
                        String isManage = userObj.getString("isManger");
                        String departcode  = userObj.getString("departcode");
                       // String roleRight  =  userObj.getString("");
                        String departType=userObj.getString("departType");
                        String appRole =userObj.getString("appRole");
                        sysUser.setUserName(userName);
                        sysUser.setDepartCode(departcode);
                        sysUser.setSysRights(roleRight);
                        sysUser.setIsManage(isManage);
                        //1县主要领导，2其他县处级领导，3乡镇，4县直单位，5管理员
                        switch (appRole){
                            case "1":
                                sysUser.setRole("县领导");
                                break;
                            case "2":
                                sysUser.setRole("其他县领导");
                                break;
                            case "3":
                                sysUser.setRole("乡镇");
                                break;
                            case "4":
                                sysUser.setRole("县直单位");
                                break;
                                case "5":
                                    sysUser.setRole("管理员");
                                break;
                                default:
                                    sysUser.setRole("管理员");
                        }

                        sysUser.setSysCode("JX");
                        sysUser.setSysName("绩效管理系统");
                    }



                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return  sysUser;
    }
    //重大系统用户信息

    private UserSystemEntity getZhongDaSysInfo(String tel)
    {

        UserSystemEntity sysUser  =null;
       // String address = "http://192.168.8.126:8585"+SystemApiUtl.ZD_GET_USERINFO+tel;
        String address = SystemApiUtl.SERVICEADDRESS+":"+SystemApiUtl.ZDTESTHOST +SystemApiUtl.ZD_GET_USERINFO;
        try {
            //String userinfo = Util.HttpGet(address, 5000, 5000);

            Object[] param = new Object[]{"phone"};
            Object[] value= new Object[]{tel};

            List<NameValuePair> nameValuePairs = HttpClientService.getParam(param, value);
            JSONObject userinfo = HttpClientService.sendGet(address, nameValuePairs, "https");
            ResultMessageDTO dto = userinfo.toJavaObject(ResultMessageDTO.class);
           // ResultMessageDTO dto = JSONObject.parseObject(userinfo, ResultMessageDTO.class);
                if("200".equals(dto.getCode()))  //获取数据
                {
                    JSONObject results = dto.getData();
                    JSONArray array  =  results.getJSONArray("list");
                    if(array.size()>0)
                    {
                        sysUser = new UserSystemEntity();
                        JSONObject userObj = (JSONObject) array.get(0);
                        String systemcode= results.getString("systemCode");
                        String systemName =results.getString("systemName");
                        String userName = userObj.getString("name");
                        String roleRight = results.getString("systemRights");
                        String departcode  = userObj.getString("departcode");
                        sysUser.setUserName(userName);
                        sysUser.setDepartCode(departcode);
                        sysUser.setSysRights(roleRight);
                        sysUser.setSysCode(systemcode);
                        sysUser.setSysName(systemName);
                    }



                }



        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("接口有误 "+address);
            return  null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        return  sysUser;
    }


    @Override
    public int saveUserSystem(List<UserSystemEntity> list) {
        int i = userMapper.saveUserSys(list);
        return i;
    }


    @Override
    public List<UserFilter> selectSysbyId(String tel) {
        return userMapper.selectSysbyId(tel);
    }
}
